﻿using System;
using log4net;
using Microsoft.Extensions.Configuration;
using SqlSugar;


namespace DISTQCPAPI.Respository
{
    public class MySqlSugarContext
    {
        private static string ip;
        private static string port;
        private static string username;
        private static string password;
        private static string database;
        private static string connectionstring;
        public static ILog iLog;
        static MySqlSugarContext()
        {
            
            var builder = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("setting.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();
             ip = string.IsNullOrEmpty(configuration.GetSection("MySQL").GetSection("IP").Value)
                ? "127.0.0.1"
                : configuration.GetSection("MySQL").GetSection("IP").Value;
            port = string.IsNullOrEmpty(configuration.GetSection("MySQL").GetSection("Port").Value)
                ? "3306"
                : configuration.GetSection("MySQL").GetSection("Port").Value;
            username = string.IsNullOrEmpty(configuration.GetSection("MySQL").GetSection("Username").Value)
                ? "root"
                : configuration.GetSection("MySQL").GetSection("Username").Value;
            password= string.IsNullOrEmpty(configuration.GetSection("MySQL").GetSection("Password").Value)
                ? "root"
                : configuration.GetSection("MySQL").GetSection("Password").Value;
            database= string.IsNullOrEmpty(configuration.GetSection("MySQL").GetSection("Database").Value)
                ? "distqcp"
                : configuration.GetSection("MySQL").GetSection("Database").Value;
            connectionstring= "server="+ip+";user id="+username+";password="+password+";persistsecurityinfo=True;database="+database+";port="+port;
            Console.WriteLine(connectionstring);
        }

        public SqlSugarClient GetClient()
        {
           var client= new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionstring, //必填
                DbType = DbType.MySql, //必填
                IsAutoCloseConnection = true, //默认false
                InitKeyType = InitKeyType.SystemTable
            }); //默认SystemTable
            if (iLog != null)
            {
                client.Aop.OnError = (exp) =>//执行SQL 错误事件
                {
                    iLog?.Error(exp.Message);

                };
            }
            if (iLog != null)
            {
                client.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
                {
                    iLog?.Info("SQL:" + sql + " ;Paras:" + pars);
                };
            }
           
            return client;
        }
    }
}
